package worker;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.jms.JMSException;

import server.GetUrl;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

public class GetUrlDetail extends TimerTask{
	static AmazonSQS sqs = null;
	static ReceiveMessageRequest receiveMessageRequest=null;
	static String myQueueUrl="https://queue.amazonaws.com/519221870477/sendurl";
	public GetUrlDetail()
	{
		sqs = new AmazonSQSClient( new BasicAWSCredentials("AKIAJO6FMN3TAI53SCHQ", "5d7Oh25MFl9M++0dCXGyBH2+6twGitftZkvYkhv7"));
		
		receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
		receiveMessageRequest.setMaxNumberOfMessages(1);
	}
	public void run()
	{
		try {
			List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
			int i=0;
            for (Message message : messages) {
            	if(i==0)
            	{
            		DBCollection collection = Data.data("logworker");
            		DBObject object = collection.findOne();
            		object.put("log", new Date());
            		collection.save(object);
            	}
            	i++;
            	
            	
            	String link = message.getBody();
            	
            	String messageRecieptHandle = message.getReceiptHandle();
                sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));
            	
                String[] arrLink = link.split("\\|");
				String sitemap = "";
				String username = "";
				String blogurl = "";
				if(arrLink.length==3)
				{
					sitemap = arrLink[0];
					username = arrLink[1];
					blogurl = arrLink[2];
				}
			
//				DBCollection coll = Data.data("urlCraw");
//				DBObject check = coll.findOne(new BasicDBObject("sitemap",sitemap).append("username", username).append("blogurl", blogurl));
				
//				if(check != null)
//				{
//					try {
////						new GetUrl(check);
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
            }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws JMSException, IOException {

		Timer timer = new Timer();
		GetContent setDataWorker = new GetContent();

	    // Schedule to run after every 3 second(3000 millisecond)

	    timer.scheduleAtFixedRate( setDataWorker, 0,10);
	}
}
